const { app, BrowserWindow, dialog, Tray, Menu, nativeImage } = require('electron');
const express = require('express');
const cors = require('cors');
const path = require('path');

let mainWindow;
let server;
let tray = null;

// 注册自定义协议
const PROTOCOL_NAME = 'rukLocalPy';

// 设置为默认协议客户端
if (process.defaultApp) {
  if (process.argv.length >= 2) {
    app.setAsDefaultProtocolClient(PROTOCOL_NAME, process.execPath, [path.resolve(process.argv[1])]);
  }
} else {
  app.setAsDefaultProtocolClient(PROTOCOL_NAME);
}

// 处理协议启动
const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
  app.quit();
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当第二个实例启动时，聚焦到现有窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore();
      mainWindow.focus();
    }
    
    // 处理协议URL
    handleProtocolUrl(commandLine);
  });

  // 处理macOS上的协议打开
  app.on('open-url', (event, url) => {
    event.preventDefault();
    handleProtocolUrl([url]);
  });
}

// 处理协议URL的函数
async function handleProtocolUrl(commandLine) {
  const url = commandLine.find(arg => arg.startsWith(`${PROTOCOL_NAME}://`));
  if (url) {
    console.log('Protocol URL received:', url);
    
    // 解析URL参数
    const urlObj = new URL(url);
    const action = urlObj.pathname.replace('/', '') || 'select-file';
    
    // 立即显示文件对话框，不等待窗口准备
    showFileDialogImmediate(action);
  }
}

// 立即显示文件对话框（协议专用，最快速度）
async function showFileDialogImmediate(action) {
  try {
    // 如果窗口不存在，快速创建一个
    if (!mainWindow || mainWindow.isDestroyed()) {
      createHiddenWindow();
    }

    let dialogWindow = mainWindow;
    
    // Windows下创建临时可见窗口
    if (process.platform === 'win32') {
      dialogWindow = createTempWindowForDialog();
      // 等待窗口准备好
      await new Promise(resolve => {
        dialogWindow.webContents.once('did-finish-load', resolve);
      });
      // 确保窗口可以支持对话框并获得最高优先级
      dialogWindow.show();
      dialogWindow.focus();
      dialogWindow.setAlwaysOnTop(true);
      app.focus({ steal: true });
      // 立即隐藏窗口但保持焦点权限
      setTimeout(() => {
        dialogWindow.hide();
      }, 100);
      await new Promise(resolve => setTimeout(resolve, 150));
    }

    // 不等待窗口加载完成，直接显示对话框
    let dialogOptions;
    
    switch (action) {
      case 'select-files':
        dialogOptions = {
          properties: ['openFile', 'multiSelections'],
          filters: [
            { name: 'All Files', extensions: ['*'] },
            { name: 'Text Files', extensions: ['txt', 'md'] },
            { name: 'Images', extensions: ['jpg', 'png', 'gif', 'bmp'] },
            { name: 'Documents', extensions: ['pdf', 'doc', 'docx'] }
          ],
          modal: false,
          alwaysOnTop: true
        };
        break;
        
      case 'select-folder':
        dialogOptions = {
          properties: ['openDirectory'],
          modal: false,
          alwaysOnTop: true
        };
        break;
        
      case 'save-file':
        dialogOptions = {
          filters: [
            { name: 'All Files', extensions: ['*'] },
            { name: 'Text Files', extensions: ['txt'] },
            { name: 'JSON Files', extensions: ['json'] }
          ],
          modal: false,
          alwaysOnTop: true
        };
        break;
        
      default: // 'select-file'
        dialogOptions = {
          properties: ['openFile'],
          filters: [
            { name: 'All Files', extensions: ['*'] },
            { name: 'Text Files', extensions: ['txt', 'md'] },
            { name: 'Images', extensions: ['jpg', 'png', 'gif', 'bmp'] },
            { name: 'Documents', extensions: ['pdf', 'doc', 'docx'] }
          ],
          modal: false,
          alwaysOnTop: true
        };
    }
    
    // 在macOS上添加默认路径
    if (process.platform === 'darwin') {
      dialogOptions.defaultPath = require('os').homedir();
      dialogOptions.securityScopedBookmarks = true;
    }
    
    // 立即显示对话框
    let result;
    if (action === 'save-file') {
      result = await dialog.showSaveDialog(dialogWindow, dialogOptions);
    } else {
      result = await dialog.showOpenDialog(dialogWindow, dialogOptions);
    }
    
    // 处理结果
    if (result && !result.canceled) {
      console.log('File dialog result:', result);
      
      // 将结果复制到剪贴板
      const { clipboard } = require('electron');
      if (result.filePaths && result.filePaths.length > 0) {
        clipboard.writeText(result.filePaths.join('\n'));
        console.log('File paths copied to clipboard:', result.filePaths);
      } else if (result.filePath) {
        clipboard.writeText(result.filePath);
        console.log('File path copied to clipboard:', result.filePath);
      }
    }

    // Windows下清理临时窗口
    if (process.platform === 'win32' && dialogWindow !== mainWindow) {
      dialogWindow.close();
    }
    
  } catch (error) {
    console.error('Error showing immediate file dialog:', error);
    // 确保临时窗口被清理
    if (process.platform === 'win32' && dialogWindow && dialogWindow !== mainWindow) {
      try {
        dialogWindow.close();
      } catch (closeError) {
        console.error('Error closing temp window:', closeError);
      }
    }
  }
}

// 创建Express服务器
const expressApp = express();
expressApp.use(cors());
expressApp.use(express.json());

// 健康检查端点
expressApp.get('/api/health', (req, res) => {
  res.json({ status: 'ok', message: 'Electron file picker service is running' });
});

// 协议测试端点
expressApp.get('/api/protocol-test', (req, res) => {
  const { action = 'select-file' } = req.query;
  const protocolUrl = `${PROTOCOL_NAME}://${action}`;
  
  res.json({ 
    success: true, 
    protocolUrl,
    message: `Protocol URL generated: ${protocolUrl}`,
    instructions: 'Copy this URL and paste it in your browser address bar to test the protocol'
  });
});

// 简化的焦点处理函数（仅用于API调用）
async function ensureWindowFocus() {
  if (!mainWindow || mainWindow.isDestroyed()) {
    return;
  }

  try {
    // 简化焦点处理，减少延迟
    if (process.platform === 'darwin') {
      // 只执行必要的焦点操作
      app.focus({ steal: true });
      mainWindow.focus();
    } else if (process.platform === 'win32') {
      // Windows简化处理 - 直接获取应用焦点
      app.focus({ steal: true });
    } else {
      mainWindow.focus();
      mainWindow.moveTop();
    }
  } catch (error) {
    console.log('Focus handling error (non-critical):', error.message);
  }
}

// 确保窗口准备就绪（用于API调用）
async function ensureWindowReady() {
  if (!mainWindow || mainWindow.isDestroyed()) {
    createHiddenWindow();
  }

  // 等待窗口完全准备就绪
  if (mainWindow.webContents.isLoading()) {
    await new Promise(resolve => {
      mainWindow.webContents.once('did-finish-load', resolve);
    });
  }

  // Windows下简化焦点处理
  if (process.platform === 'win32') {
    app.focus({ steal: true });
    await new Promise(resolve => setTimeout(resolve, 50));
  }

  // 预先获取焦点，减少后续延迟
  await ensureWindowFocus();
}

// 统一的文件对话框显示函数（用于API调用）
async function showFileDialog(type) {
  try {
    // 窗口应该已经准备就绪，直接显示对话框
    let result;
    
    switch (type) {
      case 'single':
        result = await dialog.showOpenDialog(mainWindow, {
          properties: ['openFile'],
          filters: [
            { name: 'All Files', extensions: ['*'] },
            { name: 'Text Files', extensions: ['txt', 'md'] },
            { name: 'Images', extensions: ['jpg', 'png', 'gif', 'bmp'] },
            { name: 'Documents', extensions: ['pdf', 'doc', 'docx'] }
          ],
          modal: false,
          alwaysOnTop: true,
          ...(process.platform === 'darwin' && {
            defaultPath: require('os').homedir(),
            securityScopedBookmarks: true
          })
        });
        break;
        
      case 'multiple':
        result = await dialog.showOpenDialog(mainWindow, {
          properties: ['openFile', 'multiSelections'],
          filters: [
            { name: 'All Files', extensions: ['*'] },
            { name: 'Text Files', extensions: ['txt', 'md'] },
            { name: 'Images', extensions: ['jpg', 'png', 'gif', 'bmp'] },
            { name: 'Documents', extensions: ['pdf', 'doc', 'docx'] }
          ],
          modal: false,
          alwaysOnTop: true,
          ...(process.platform === 'darwin' && {
            defaultPath: require('os').homedir(),
            securityScopedBookmarks: true
          })
        });
        break;
        
      case 'folder':
        result = await dialog.showOpenDialog(mainWindow, {
          properties: ['openDirectory'],
          modal: false,
          alwaysOnTop: true,
          ...(process.platform === 'darwin' && {
            defaultPath: require('os').homedir(),
            securityScopedBookmarks: true
          })
        });
        break;
        
      case 'save':
        result = await dialog.showSaveDialog(mainWindow, {
          filters: [
            { name: 'All Files', extensions: ['*'] },
            { name: 'Text Files', extensions: ['txt'] },
            { name: 'JSON Files', extensions: ['json'] }
          ],
          modal: false,
          alwaysOnTop: true,
          ...(process.platform === 'darwin' && {
            defaultPath: require('os').homedir(),
            securityScopedBookmarks: true
          })
        });
        break;
    }
    
    if (result && !result.canceled) {
      console.log('File dialog result:', result);
      
      // 将结果复制到剪贴板
      const { clipboard } = require('electron');
      if (result.filePaths && result.filePaths.length > 0) {
        clipboard.writeText(result.filePaths.join('\n'));
        console.log('File paths copied to clipboard:', result.filePaths);
      } else if (result.filePath) {
        clipboard.writeText(result.filePath);
        console.log('File path copied to clipboard:', result.filePath);
      }
    }
    
  } catch (error) {
    console.error('Error showing file dialog:', error);
  }
}

// 文件选择API端点 - 优化版本
expressApp.post('/api/select-file', async (req, res) => {
  try {
    // 确保窗口准备就绪
    await ensureWindowReady();

    let dialogWindow = mainWindow;
    
    // Windows下创建临时可见窗口
    if (process.platform === 'win32') {
      dialogWindow = createTempWindowForDialog();
      // 等待窗口准备好
      await new Promise(resolve => {
        dialogWindow.webContents.once('did-finish-load', resolve);
      });
      await new Promise(resolve => setTimeout(resolve, 200));
    }

    const result = await dialog.showOpenDialog(dialogWindow, {
      properties: ['openFile'],
      filters: [
        { name: 'All Files', extensions: ['*'] },
        { name: 'Text Files', extensions: ['txt', 'md'] },
        { name: 'Images', extensions: ['jpg', 'png', 'gif', 'bmp'] },
        { name: 'Documents', extensions: ['pdf', 'doc', 'docx'] }
      ],
      modal: false,
      alwaysOnTop: true,
      ...(process.platform === 'darwin' && {
        defaultPath: require('os').homedir(),
        securityScopedBookmarks: true
      })
    });

    // Windows下清理临时窗口
    if (process.platform === 'win32' && dialogWindow !== mainWindow) {
      dialogWindow.close();
    }

    if (result.canceled) {
      res.json({ success: false, message: 'File selection canceled' });
    } else {
      res.json({
        success: true,
        filePath: result.filePaths[0],
        message: 'File selected successfully'
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: 'Error selecting file',
      error: error.message
    });
  }
});

// 多文件选择API端点 - 优化版本
expressApp.post('/api/select-files', async (req, res) => {
  try {
    await ensureWindowReady();

    let dialogWindow = mainWindow;
    
    // Windows下创建临时可见窗口
    if (process.platform === 'win32') {
      dialogWindow = createTempWindowForDialog();
      await new Promise(resolve => {
        dialogWindow.webContents.once('did-finish-load', resolve);
      });
      // 确保窗口可以支持对话框
      dialogWindow.show();
      dialogWindow.focus();
      dialogWindow.setAlwaysOnTop(true);
      app.focus({ steal: true });
      // 立即隐藏窗口但保持焦点权限
      setTimeout(() => {
        dialogWindow.hide();
      }, 100);
      await new Promise(resolve => setTimeout(resolve, 150));
    }

    const result = await dialog.showOpenDialog(dialogWindow, {
      properties: ['openFile', 'multiSelections'],
      filters: [
        { name: 'All Files', extensions: ['*'] },
        { name: 'Text Files', extensions: ['txt', 'md'] },
        { name: 'Images', extensions: ['jpg', 'png', 'gif', 'bmp'] },
        { name: 'Documents', extensions: ['pdf', 'doc', 'docx'] }
      ],
      modal: false,
      alwaysOnTop: true,
      ...(process.platform === 'darwin' && {
        defaultPath: require('os').homedir(),
        securityScopedBookmarks: true
      })
    });

    // Windows下清理临时窗口
    if (process.platform === 'win32' && dialogWindow !== mainWindow) {
      dialogWindow.close();
    }

    if (result.canceled) {
      res.json({ success: false, message: 'File selection canceled' });
    } else {
      res.json({
        success: true,
        filePaths: result.filePaths,
        message: 'Files selected successfully'
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: 'Error selecting files',
      error: error.message
    });
  }
});

// 文件夹选择API端点 - 优化版本
expressApp.post('/api/select-folder', async (req, res) => {
  try {
    await ensureWindowReady();

    let dialogWindow = mainWindow;
    
    // Windows下创建临时可见窗口
    if (process.platform === 'win32') {
      dialogWindow = createTempWindowForDialog();
      await new Promise(resolve => {
        dialogWindow.webContents.once('did-finish-load', resolve);
      });
      // 确保窗口可以支持对话框
      dialogWindow.show();
      dialogWindow.focus();
      dialogWindow.setAlwaysOnTop(true);
      app.focus({ steal: true });
      // 立即隐藏窗口但保持焦点权限
      setTimeout(() => {
        dialogWindow.hide();
      }, 100);
      await new Promise(resolve => setTimeout(resolve, 150));
    }
    
    const result = await dialog.showOpenDialog(dialogWindow, {
      properties: ['openDirectory'],
      modal: false,
      alwaysOnTop: true,
      ...(process.platform === 'darwin' && {
        defaultPath: require('os').homedir(),
        securityScopedBookmarks: true
      })
    });

    // Windows下清理临时窗口
    if (process.platform === 'win32' && dialogWindow !== mainWindow) {
      dialogWindow.close();
    }

    if (result.canceled) {
      res.json({ success: false, message: 'Folder selection canceled' });
    } else {
      res.json({ 
        success: true, 
        folderPath: result.filePaths[0],
        message: 'Folder selected successfully' 
      });
    }
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      message: 'Error selecting folder', 
      error: error.message 
    });
  }
});

// 保存文件对话框API端点 - 优化版本
expressApp.post('/api/save-file', async (req, res) => {
  try {
    await ensureWindowReady();

    let dialogWindow = mainWindow;
    
    // Windows下创建临时可见窗口
    if (process.platform === 'win32') {
      dialogWindow = createTempWindowForDialog();
      await new Promise(resolve => {
        dialogWindow.webContents.once('did-finish-load', resolve);
      });
      // 确保窗口可以支持对话框
      dialogWindow.show();
      dialogWindow.focus();
      dialogWindow.setAlwaysOnTop(true);
      app.focus({ steal: true });
      // 立即隐藏窗口但保持焦点权限
      setTimeout(() => {
        dialogWindow.hide();
      }, 100);
      await new Promise(resolve => setTimeout(resolve, 150));
    }
    
    const result = await dialog.showSaveDialog(dialogWindow, {
      filters: [
        { name: 'All Files', extensions: ['*'] },
        { name: 'Text Files', extensions: ['txt'] },
        { name: 'JSON Files', extensions: ['json'] }
      ],
      modal: false,
      alwaysOnTop: true,
      ...(process.platform === 'darwin' && {
        defaultPath: require('os').homedir(),
        securityScopedBookmarks: true
      })
    });

    // Windows下清理临时窗口
    if (process.platform === 'win32' && dialogWindow !== mainWindow) {
      dialogWindow.close();
    }

    if (result.canceled) {
      res.json({ success: false, message: 'Save dialog canceled' });
    } else {
      res.json({ 
        success: true, 
        filePath: result.filePath,
        message: 'Save path selected successfully' 
      });
    }
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      message: 'Error in save dialog', 
      error: error.message 
    });
  }
});

// 创建隐藏的窗口（仅用于文件对话框）- 最优化版本
function createHiddenWindow() {
  const windowOptions = {
    width: 1,
    height: 1,
    show: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      backgroundThrottling: false, // 防止后台节流
      offscreen: false // 确保不是离屏渲染
    },
    title: 'File Picker Service',
    skipTaskbar: true,
    transparent: true,
    frame: false,
    alwaysOnTop: false,
    focusable: true, // 确保可以获得焦点
    ...(process.platform === 'darwin' && {
      titleBarStyle: 'hidden'
    })
  };

  // Windows特殊配置 - 简化但有效
  if (process.platform === 'win32') {
    windowOptions.show = false; // 不显示窗口
    windowOptions.width = 1;
    windowOptions.height = 1;
    windowOptions.frame = false; // 无框架
    windowOptions.transparent = true;
    windowOptions.skipTaskbar = true; // 不在任务栏显示
    windowOptions.focusable = true; // 保持可获得焦点
    windowOptions.webSecurity = false; // 简化安全设置
  }

  mainWindow = new BrowserWindow(windowOptions);

  // 加载最简单的页面
  mainWindow.loadURL('data:text/html,<html><body></body></html>');

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  // 窗口准备就绪后的回调
  mainWindow.webContents.once('did-finish-load', () => {
    console.log('Hidden window ready for file dialogs');
  });
}

// Windows专用：创建临时可见窗口用于文件对话框
function createTempWindowForDialog() {
  if (process.platform !== 'win32') {
    return mainWindow;
  }

  const tempWindow = new BrowserWindow({
    width: 1,
    height: 1,
    show: false, // 不显示窗口
    frame: false,
    transparent: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    title: 'File Picker',
    skipTaskbar: true, // 不在任务栏显示
    focusable: true,
    alwaysOnTop: true, // 设置为置顶，确保对话框在最前面
    opacity: 0 // 完全透明
  });

  // 加载空页面
  tempWindow.loadURL('data:text/html,<html><body></body></html>');
  
  // 窗口准备好后的处理
  tempWindow.once('ready-to-show', () => {
    // 临时显示窗口以获得焦点和置顶权限
    tempWindow.show();
    tempWindow.focus();
    tempWindow.setAlwaysOnTop(true);
    // 立即隐藏但保持活跃状态
    setTimeout(() => {
      tempWindow.hide();
    }, 50);
  });
  
  return tempWindow;
}

// 创建系统托盘
function createTray() {
  try {
    // 尝试加载SVG图标
    const iconPath = path.join(__dirname, 'assets', 'tray-icon.svg');
    console.log('Loading tray icon from:', iconPath);
    
    // 创建托盘图标
    const icon = nativeImage.createFromPath(iconPath);
    if (icon.isEmpty()) {
      console.log('SVG icon failed, using default icon');
      // 如果SVG图标加载失败，创建一个简单的默认图标
      const defaultIcon = nativeImage.createFromDataURL('');
      tray = new Tray(defaultIcon);
    } else {
      tray = new Tray(icon);
    }
    
    // 设置托盘图标的工具提示
    tray.setToolTip('文件选择服务');
    
    // 创建托盘菜单
    const contextMenu = Menu.buildFromTemplate([
      {
        label: '显示主窗口',
        click: () => {
          if (mainWindow) {
            mainWindow.show();
            mainWindow.focus();
          } else {
            createMainWindow();
          }
        }
      },
      {
        type: 'separator'
      },
      {
        label: '选择文件',
        click: () => {
          showFileDialogImmediate('select-file');
        }
      },
      {
        label: '选择多个文件',
        click: () => {
          showFileDialogImmediate('select-files');
        }
      },
      {
        label: '选择文件夹',
        click: () => {
          showFileDialogImmediate('select-folder');
        }
      },
      {
        label: '保存文件',
        click: () => {
          showFileDialogImmediate('save-file');
        }
      },
      {
        type: 'separator'
      },
      {
        label: '退出',
        click: () => {
          app.quit();
        }
      }
    ]);
    
    // 设置托盘菜单
    tray.setContextMenu(contextMenu);
    
    // 双击托盘图标显示主窗口
    tray.on('double-click', () => {
      if (mainWindow) {
        if (mainWindow.isMinimized() || !mainWindow.isVisible()) {
          mainWindow.show();
          mainWindow.focus();
        } else {
          mainWindow.hide();
        }
      } else {
        createMainWindow();
      }
    });
    
    console.log('System tray created successfully');
  } catch (error) {
    console.error('Failed to create system tray:', error);
  }
}

// 创建主窗口（可见窗口）
function createMainWindow() {
  if (mainWindow && !mainWindow.isDestroyed()) {
    mainWindow.show();
    mainWindow.focus();
    return;
  }
  
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    show: false, // 默认不显示
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    title: '文件选择服务',
    icon: path.join(__dirname, 'assets', 'tray-icon.svg')
  });

  // 加载一个简单的HTML页面
  mainWindow.loadURL('data:text/html,<!DOCTYPE html><html><head><meta charset="UTF-8"><title>文件选择服务</title><style>body{font-family:Arial,sans-serif;margin:40px;background:#f5f5f5;}h1{color:#333;}.status{background:white;padding:20px;border-radius:8px;box-shadow:0 2px 4px rgba(0,0,0,0.1);}.button{background:#2196F3;color:white;border:none;padding:10px 20px;margin:10px 5px;border-radius:4px;cursor:pointer;}.button:hover{background:#1976D2;}</style></head><body><h1>文件选择服务</h1><div class="status"><p>服务正在运行中...</p><p>端口: 3001</p><p>协议: rukLocalPy://</p><button class="button" onclick="window.close()">最小化到托盘</button></div></body></html>');

  // 窗口关闭时隐藏到托盘而不是退出
  mainWindow.on('close', (event) => {
    if (!app.isQuiting) {
      event.preventDefault();
      mainWindow.hide();
      return false;
    }
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  // 准备显示时才显示窗口
  mainWindow.once('ready-to-show', () => {
    console.log('Main window ready');
  });
}

// 应用准备就绪时
app.whenReady().then(() => {
  console.log('Electron app starting...');
  console.log(`Protocol registered: ${PROTOCOL_NAME}://`);
  
  // 创建系统托盘
  createTray();
  
  // 检查是否通过协议启动
  if (process.argv.length >= 2) {
    handleProtocolUrl(process.argv);
  }
  
  // 创建隐藏窗口用于文件对话框
  createHiddenWindow();
  
  // 启动Express服务器
  const PORT = 3001;
  server = expressApp.listen(PORT, () => {
    console.log(`File picker service running on port ${PORT}`);
    console.log(`Protocol test URL: http://localhost:${PORT}/api/protocol-test`);
    console.log('应用已启动并最小化到系统托盘');
  });

  app.on('activate', () => {
    // macOS上点击dock图标时显示主窗口
    if (mainWindow) {
      mainWindow.show();
      mainWindow.focus();
    } else {
      createMainWindow();
    }
  });
});

// 所有窗口关闭时
app.on('window-all-closed', () => {
  // 不要退出应用，保持在系统托盘中运行
  // 只有在显式调用app.quit()时才真正退出
});

// 应用退出前
app.on('before-quit', (event) => {
  app.isQuiting = true;
  
  if (server) {
    server.close();
  }
  
  // 销毁系统托盘
  if (tray) {
    tray.destroy();
  }
});

console.log('Script loaded'); 